import {MessageBox, Message} from 'element-ui'

/**
 * 封装fetch
 * @param url
 * @param opt {method, headers, body, type, ...rest}
 * @returns {Promise<any>}
 */
export default (url, opt) => {
    const isObj = obj => Object.prototype.toString.call(obj) === '[object Object]';
    return new Promise((resolve, reject) => {
        if (!isObj(opt)) {
            opt = {};
        }
        let base = process.env.BASE_API;
        // 可以传入请求必需的头字段
        let headers = new Headers({});
        if (isObj(opt.headers)) {
            for (let k in opt.headers) {
                headers.set(k, opt.headers[k]);
            }
        }
        Reflect.deleteProperty(opt, 'headers');
        if (!opt.method || opt.method === 'GET') {
            if (isObj(opt.body)) {
                let arr = [];
                for (let k in opt.body) {
                    if (typeof opt.body[k] !== 'undefined') {
                        arr.push(`${k}=${opt.body[k]}`);
                    }
                }
                if (arr.length > 0) {
                    url += `?${arr.join('&')}`;
                }
            }
            Reflect.deleteProperty(opt, 'body');
        } else {
            if (!opt.type || opt.type === 'json') {
                headers.set('Content-Type', 'application/json;charset=UTF-8');
                opt.body = JSON.stringify(opt.body);
            } else if (opt.type === 'form') {
                headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
                let arr = [];
                for (let k in opt.body) {
                    if (typeof opt.body[k] !== 'undefined') {
                        arr.push(`${k}=${opt.body[k]}`);
                    }
                }
                opt.body = arr.join('&');
            } else if (opt.type === 'file') {
                let form = new FormData();
                for (let k in opt.body) {
                    if (typeof opt.body[k] !== 'undefined') {
                        form.append(k, opt.body[k]);
                    }
                }
                opt.body = form;
            }
        }
        const req = new Request(base + url, {
            method: 'GET',
            mode: 'cors',
            cache: 'default',
            // credentials: 'include',
            ...opt,
            headers
        });
        fetch(req).then(res => {
            if (!res.ok) {
                reject();
                return false;
            }
            res.json().then(json => {
                if (json.status === 200) {
                    resolve(json);
                    return false;
                }
                if (json.status === 530) {
                    let timer = setTimeout(() => {
                        clearTimeout(timer);
                        location.href = '/login';
                    }, 1500);
                    MessageBox.alert('登录超时, 请重新登录', '提示').then(() => {
                        location.href = '/login';
                    });
                    return false;
                }
                /*if (json.status === 1001) {
                    let timer = setTimeout(() => {
                        clearTimeout(timer);
                        history.go(-1);
                    }, 1500);
                    MessageBox.alert(json.msg, '提示').then(() => {
                        history.go(-1);
                    });
                    return false;
                }*/
                Message.error(json.msg);
                reject(json.msg);
            });
        }).catch(err => {
            reject(err);
        });
    });
}